package com.hog.service.qiniu.impl;

import com.alibaba.fastjson.JSONObject;
import com.hog.service.qiniu.IQiniuHandleService;
import com.hog.utils.ImgUtil;
import com.hog.utils.StringUtils;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;


/**
 * 七牛相关处理Service
 *
 * @author 唐晴
 * @date 2020年08月06日
 * @since JDK 1.8
 */
@Service
@Slf4j
public class QiniuHandleServiceImpl implements IQiniuHandleService {

    @Override
    public PutRet uploadImg(String src) throws Exception {
        String accessKey = "gq70haev-RbHoLLQ7pG1Ls7yCnDfOT03Wk9Yk6Fs";
        String secretKey = "v1t6QzD0HbnBR9twlFLJTwzEe8zv1e76gckgwQJz";
        Mac mac = new Mac(accessKey, secretKey);
        // 请确保该bucket已经存在
        String bucketName = "tqcto-img";
        PutPolicy putPolicy = new PutPolicy(bucketName);
        String uptoken = putPolicy.token(mac);
        PutExtra extra = new PutExtra();
        String key = String.format("%s.jpg", StringUtils.emptyIfNull(System.currentTimeMillis()));
        InputStream inputStream = ImgUtil.getUrlPic(src);
        PutRet ret = IoApi.Put(uptoken, key, inputStream, extra);
        log.info("图片上传结果: {}", JSONObject.toJSONString(ret));
        return ret;
    }
}